package com.rxnetwork.sample.application;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.rxnetwork.manager.RxNetWork;
import com.rxnetwork.sample.api.Api;
import com.rxnetwork.sample.crash.Cockroach;
import com.rxnetwork.sample.crash.CrashHandler;
import com.rxnetwork.sample.utils.interceptor.AppCacheInterceptor;
import com.rxnetwork.sample.utils.interceptor.AppHeaderInterceptor;
import com.rxnetwork.sample.utils.interceptor.AppLogInterceptor;

import okhttp3.Cache;

public class App extends Application {

    private int mbuild = 0;
    private String mHost;

    @Override
    public void onCreate() {
        super.onCreate();
        /**
         * 建议这里设置统一设置参数
         */
        switch (mbuild){
            case 0:
                mHost = Api.LOCAL_HOST;
                break;
            case 1:
                mHost = Api.TEST_URL;
                break;
            case 2:
                mHost = Api.TEST2_URL;
                break;
            case 3:
                mHost = Api.ZL_BASE_API;
                break;
        }
        RxNetWork
                .getInstance()
                .setBaseUrl(mHost)
                .setTimeoutTime(30)
                .setLogInterceptor(new AppLogInterceptor())
                .setHeaderInterceptor(new AppHeaderInterceptor())
                .setCache(new Cache(getApplicationContext().getCacheDir(), 1024 * 1024 * 10))//缓存大小10M
                .setCacheInterceptor(new AppCacheInterceptor(getApplicationContext()))
                .setRetryOnConnectionFailure(true);

        initCrash();
    }

    private void initCrash() {
        Cockroach.install(new Cockroach.ExceptionHandler() {
            // handlerException内部建议手动try{  你的异常处理逻辑  }catch(Throwable e){ } ，以防handlerException内部再次抛出异常，导致循环调用handlerException
            @Override
            public void handlerException(final Thread thread, final Throwable throwable) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //控制台打印crash
                            throwable.printStackTrace();
                            //log打印crash
                            Log.e("Cockroach", thread + "\n" + throwable.toString());
                            //吐司crash
//                            Toast.makeText(App.this, "Exception Happend\n" + thread + "\n" + throwable.toString(), Toast.LENGTH_SHORT).show();
                            //本地保存crash
                            CrashHandler.getInstance().saveCrashInfo2File(App.this, throwable);
                        } catch (Throwable e) {
                        }
                    }
                });
            }
        });
        // 卸载代码
//        Cockroach.uninstall();
    }

}
